﻿using CatUtils.Utils.Currency;
using CatUtils.Utils.Currency.IoUtils;
using CatUtils.Utils.Currency.TextUtils;

using CatUtils.Utils.Helper;
using CatUtils.Utils.SpecialUtils.Html;
using CatUtils.Utils.SpecialUtils.View;
using CatUtilsDll.Utils.Currency.WebUtils;
using Newtonsoft.Json;
using RabbitDownload.Helper;
using RabbitDownload.Helper.Currency;

using System;
using System.Net;
using System.Windows.Forms;

namespace RabbitDownload.WebSite.Pixiv.Login
{
    internal class LoginHelper
    {
        /// <summary>
        /// 缓存登录用户数据
        /// </summary>
   //     public static Helper.Currency.CookiesWebclient.CWebclient LocalClient = new Helper.Currency.CookiesWebclient.CWebclient();

        public static string UserInfoPath = StaticValue.BinPath + "PixivUserInfo.json";

        internal static void InitUserInfo(TextBox textBox1, TextBox textBox2)
        {
            try
            {
                UserInfo ReadJson = JsonConvert.DeserializeObject<UserInfo>(FileHelper.ReadAllText(UserInfoPath));
                textBox1.Text = ReadJson.UserName1;
                textBox2.Text = ReadJson.Password1;
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
                Console.WriteLine("无用户信息文件，无法加载。");
            }
        }

        public static WebHeaderCollection InitHeader()
        {
            WebHeaderCollection webHeader = WebHelper.PcWebHeader();
            webHeader.Add("x-user-id", "24587510");
            webHeader.Add("Referer", "https://www.pixiv.net/");

            webHeader.Add("Cookie", PixivStaticValue.GetPixivCookies());
            return webHeader;
        }

        /// <summary>
        /// 读取本地用户名登录，若登录失败返回null
        /// </summary>
        /// <returns></returns>
        internal CWebclient AutoLogin()
        {
            try
            {
                CWebclient cWebclient = new CWebclient();
                cWebclient.Headers = WebHelper.PcWebHeader();

                cWebclient.Headers.Add("x-user-id", "24587510");
                cWebclient.Headers.Add("Referer", "https://www.pixiv.net/");
                Console.WriteLine("COOKIES" + PixivStaticValue.GetPixivCookies());
                cWebclient.Headers.Add("Cookie", PixivStaticValue.GetPixivCookies());
                return cWebclient;
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
                MessageHelper.DialogResultAlert("启动登录失败，请重新设置账号！");
            }
            return null;
        }

        /// <summary>
        /// 登录并返回登录状态
        /// </summary>
        /// <param name="UserName"></param>
        /// <param name="PassWord"></param>
        internal CWebclient StartLogin(string UserName, string PassWord)
        {
            CWebclient cWebclient = new CWebclient();
            if (UserName == "" || PassWord == "")
            {
                MessageHelper.Alert("用户名或密码不能为空！");
                return null;
            }

            UserName = WebHelper.UrlEncode(UserName);
            PassWord = WebHelper.UrlEncode(PassWord);
            String Shtml = cWebclient.GetHtml(LoginStaticValue.LoginIndex, WebHelper.PcWebHeader());
            Console.WriteLine(UserName);
            Console.WriteLine(PassWord);

            string PostKey = HtmlHelper.GetFirstAttributes(Shtml, "value", "//input[@name='post_key']");
            Console.WriteLine(PostKey);
            Console.WriteLine(UserName);
            Console.WriteLine(PassWord);
            String PostDataMode = "pixiv_id={0}&captcha=&g_recaptcha_response=&password={1}&post_key={2}&source=pc&ref=wwwtop_accounts_index&return_to=https%3A%2F%2Fwww.pixiv.net%2F";
            String PostData = string.Format(PostDataMode, UserName, PassWord, PostKey);
            string LoginReq = cWebclient.SendPost(LoginStaticValue.LoginPostTo, PostData, LoginStaticValue.GetPostHeader());

            Console.WriteLine(LoginReq);
            if (Analysis(LoginReq))
                return cWebclient;
            return null;
        }

        /// <summary>
        /// 用于分析是否登陆成功 成功返回true
        /// </summary>
        /// <param name="loginReq"></param>
        /// <returns></returns>
        private bool Analysis(string loginReq)
        {
            try
            {
                LoginStaticValue.PixivLoginJson.Root LoginJson = JsonConvert.DeserializeObject<LoginStaticValue.PixivLoginJson.Root>(loginReq);
                Console.WriteLine("模拟登陆{0}完毕", LoginJson.body.success.return_to);
                return true;
            }
            catch (Exception ex)
            {
                try
                {
                    LoginStaticValue.LoginSucess.Root LoginJson = JsonConvert.DeserializeObject<LoginStaticValue.LoginSucess.Root>(loginReq);
                    Console.WriteLine("二次登陆：{0}完毕", LoginJson.body.validation_errors.etc);
                    return true;
                }
                catch (Exception ex2)
                {
                    MessageHelper.Alert("登录失败！" + ex.Message);
                    PrintLog.Log(ex);
                    PrintLog.Log(ex2);
                    PrintLog.Log(loginReq);
                }
            }
            return false;
        }

        private class UserInfo
        {
            private string UserName;
            private string Password;

            public string UserName1 { get => UserName; set => UserName = value; }
            public string Password1 { get => Password; set => Password = value; }
        }

        internal static void SaveUserInfo(string UserName, string PassWord)
        {
            UserInfo product = new UserInfo();
            product.UserName1 = UserName;
            product.Password1 = PassWord;

            string json = JsonConvert.SerializeObject(product);
            FileHelper.WriteText(UserInfoPath, json);
        }
    }
}